/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2007 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is part of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.elf.gwt.store.client.subcomponents;

import java.util.Iterator;
import java.util.List;

import com.elf.gwt.common.client.callback.SubComponentCallback;
import com.elf.gwt.common.client.model.CheckoutModel;
import com.elf.gwt.common.client.model.ShippingModel;
import com.elf.gwt.common.client.model.ShippingRateModel;
import com.elf.gwt.common.client.utils.CommonUtils;
import com.elf.gwt.store.client.GWTCommerceModuleConstants;
import com.elf.gwt.store.client.StoreComponentController;
import com.elf.gwt.store.client.components.CurrenciesComponent;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.InlineHTML;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.RadioButton;

/**
 *  Subcomponent for logging into application
 */
public class CheckoutShippingSubComponent extends CheckoutSubComponent
{
	protected String selectedTitle = "";
	protected boolean checkoutCompleted;

	/**
	 * Constructor
	 */
	public CheckoutShippingSubComponent(
			StoreComponentController controller, 
			SubComponentCallback callback)
	{
		super(controller, null, callback);
		if (currenciesComponent == null) currenciesComponent = (CurrenciesComponent)controller.getComponent("CurrenciesComponent");
	}

	/**
	 * build
	 */
	public void build() 
	{
		CheckoutModel checkoutModel = checkoutComponent.getCheckoutModel();
		
		thisComponent.clear();

		NumberFormat weightFormat = NumberFormat.getFormat("#.##");
		GWTCommerceModuleConstants moduleConstants = controller.getStoreModuleConstants();

		List<ShippingModel> shippings = checkoutComponent.getCheckoutModel().getShippings();
		
		boolean useCheapest = checkoutModel.isShippingUseCheapest();
				
		if (checkoutCompleted)
		{
			String shippingModule = checkoutModel.getSelectedShippingModule();
			String shippingTitle = shippingModule;
			try {
				shippingTitle = moduleConstants.getString("Shipping_" + shippingTitle);
			} catch (Exception e){}

			String shippingService = checkoutModel.getSelectedShippingService();
			try {
				//underscores for spaces
				String strTmp = "Shipping_" + shippingModule + "_" + shippingService;
				strTmp = strTmp.replace(' ', '_');
				shippingService = moduleConstants.getString(strTmp);
				GWT.log(shippingService);
			} catch (Exception e){}

			if (!shippingModule.equals("free")) {
				String strWeight = weightFormat.format(shippings.get(0).getWeight());
				shippingTitle = shippingTitle + " (" + shippings.get(0).getNumBoxes() + " X " + strWeight + " lbs) " + shippingService;
			}

			Grid grid = new Grid(1,2);
			grid.setStyleName(handle + "SubPanel");
			grid.getColumnFormatter().setStyleName(0, handle + "SubPanelCol0");
			grid.getCellFormatter().setWidth(0, 1, "100%");
			InlineLabel label = new InlineLabel(shippingTitle);
			grid.setWidget(0, 1, label);
			thisComponent.add(grid);
			thisComponent.add(new InlineHTML("<br/>"));
		}
		else
		{
			for (Iterator<ShippingModel> iter = shippings.iterator(); iter.hasNext(); )
			{
				ShippingModel shipping = iter.next();
				String shippingTitle = shipping.getModule();
				if (useCheapest && !shippingTitle.equals(checkoutModel.getSelectedShippingModule())) continue;

				try {
					shippingTitle = moduleConstants.getString("Shipping_" + shippingTitle);
				} catch (Exception e){}

				if (!shipping.getModule().equals("free")) {
					String strWeight = weightFormat.format(shippings.get(0).getWeight());
					shippingTitle = shippingTitle + " (" + shipping.getNumBoxes() + " X " + strWeight + " lbs) ";
				}
				CommonUtils.addSubTitle(handle, thisComponent, shippingTitle);

				String imageName = "";
				try {
					imageName = moduleConstants.getString("Shipping_" + shipping.getModule() + "_icon").trim();
				}
				catch (Exception e){};
				if (imageName.length() > 0)
				{
					Image image = new Image(getImageDirectory() + imageName);
					thisComponent.add(image);
				}

				thisComponent.add(new InlineHTML("<br/>"));

				double handling = shipping.getHandling();

				Grid rateGrid = new Grid(shipping.getRates().size(), 3);
				rateGrid.setStyleName(handle + "SubPanel");
				rateGrid.getColumnFormatter().setStyleName(0, handle + "SubPanelCol0");
				int i = 0;
				for (Iterator<ShippingRateModel> iter1 = shipping.getRates().iterator(); iter1.hasNext(); )
				{
					ShippingRateModel rate = iter1.next();
					String shippingService = rate.getService();
					
					if (useCheapest && !shippingService.equals(checkoutModel.getSelectedShippingService())) continue;
					
					try {
						//underscores for spaces
						String strTmp = "Shipping_" + shipping.getModule() + "_" + rate.getService();
						strTmp = strTmp.replace(' ', '_');
						shippingService = moduleConstants.getString(strTmp);
						GWT.log(shippingService);
					} catch (Exception e){}

					RadioButton selectButton = new RadioButton("shipping_service");
					selectButton.setTitle(shipping.getModule() + "|" + rate.getService());
					if (shipping.getModule().equals(checkoutModel.getSelectedShippingModule()) && rate.getService().equals(checkoutModel.getSelectedShippingService()))
					{
						selectButton.setValue(true);
						selectedTitle = shippingTitle;
					}
					
					selectButton.addClickHandler(
							new ClickHandler() {
								public void onClick(ClickEvent event) {
									CheckoutModel checkoutModel = checkoutComponent.getCheckoutModel();
									RadioButton button = (RadioButton)event.getSource();
									if (button.getValue())
									{
										String name = button.getTitle();
										int index = name.indexOf("|");
										String module = name.substring(0, index);
										String service = name.substring(index+1);
										checkoutModel.setSelectedShippingModule(module);
										checkoutModel.setSelectedShippingService(service);
										callback.onSuccess(thisComponent);
									}
								}});
					selectButton.setVisible(!checkoutCompleted);
					rateGrid.setWidget(i, 0, selectButton);
					double shippingPrice = (rate.getPostage() + handling) * shipping.getNumBoxes();
					rateGrid.setHTML(i, 1, CommonUtils.priceDisplay(currenciesComponent.getCurrencyModel(), shippingPrice));
					rateGrid.getCellFormatter().setWidth(i, 1, "80px");
					rateGrid.setText(i, 2, shippingService);
					rateGrid.getCellFormatter().setWidth(i, 2, "100%");
					i++;
				}
				thisComponent.add(rateGrid);

				thisComponent.add(new InlineHTML("<br/>"));
			}
		}
	}
	
	public String validate(String action)
	{
		return "";
	}

	public String getSelectedTitle() {
		return selectedTitle;
	}

	public boolean isCheckoutCompleted() {
		return checkoutCompleted;
	}

	public void setCheckoutCompleted(boolean checkoutCompleted) {
		this.checkoutCompleted = checkoutCompleted;
	}
}
